package com.chinasofti.project.web.common;

import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import com.chinasofti.project.common.Constants;
import com.chinasofti.project.common.result.ExecuteResult;
import com.chinasofti.project.enums.AppResultCode;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * 全局异常处理，将系统异常和业务异常区分处理 Created by Lucas on 2017-02-21.
 */
@ControllerAdvice
public class GlobalExceptionHandler {
	private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
	private static final String DEFAULT_ERROR_PAGE = "error";

	@ExceptionHandler(Exception.class)
	public String logException(Exception e, HttpServletRequest request, HttpServletResponse response,Model model) {
		logger.error("系统异常被捕获", e);
		String requestType = request.getHeader("X-Requested-With");

		if ("XMLHttpRequest".equals(requestType)) {
			OutputStream responseBodyOut;
			try {
				responseBodyOut = response.getOutputStream();
				handleAjaxRequest(e, responseBodyOut);
			} catch (IOException e1) {
				logger.error("输出错误出错",e1);
			}
			return null;
		}else{
			model.addAttribute(Constants.ERROR_MSG_KEY, "系统异常,["+e.getMessage()+"]");
		}
		
		return  DEFAULT_ERROR_PAGE;
	}

	private void handleAjaxRequest(Exception e, OutputStream responseBodyOut) {
		// ajax异常处理,返回一个错误结果
		ExecuteResult result = ExecuteResult.failResult(AppResultCode.SYS_ERROR.getCode(), e.getMessage());
		ObjectMapper mapper = new ObjectMapper();
		try {
			String jsonInString = mapper.writeValueAsString(result);
			responseBodyOut.write(jsonInString.getBytes());
		} catch (IOException e2) {
			logger.error("写出json错误提示时报错", e2);
		}
	}

}
